<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!</title>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
<script src="https://cdn.bootcss.com/prop-types/15.6.1/prop-types.js"></script>
</head>
<body>

<div id="example"></div>
<script type="text/babel">
	
	class App extends React.Component{
		constructor(props) {
		    super(props)
			this.state={
				todos:['吃饭','睡觉','打豆豆']
			}
			this.addTodo = this.addTodo.bind(this)
		}

		addTodo(todo){
			const {todos} = this.state
			todos.unshift(todo)
			//更新状态
			this.setState({todos})
		}
		render(){
			return(
				<div>
					<h1>Simple TODO List</h1>
					<Add count={this.state.todos.length} addTodo={this.addTodo}/>
					<List todos={this.state.todos} />
				</div>
			)
		}
	}
	class Add extends React.Component{
		constructor(props){
			super(props)
			this.add=this.add.bind(this)
		}
		add(){
			//需要在子组件中改变父组件状态:
			//父组件定义函数，传递给子组件，子组件调用
			//1.读取输入数据
			const todo = this.todoInput.value.trim();
			//2.检查合法性，添加
			if(!todo){return}
			this.props.addTodo(todo)
			//清除输入
			this.todoInput.value='';
		}
		render(){
			return(
			<div>
				<input type='text' ref={input=>this.todoInput=input}/>
				<button onClick={this.add}>add #{this.props.count+1}</button>
			</div>
				)
		}
	}
	Add.prototypes={
		todos:PropTypes.number.isRequired,
		addTodo:PropTypes.func.isRequired
	}
	class List extends React.Component{
		render(){
			return(
				<ul>
					{this.props.todos.map((todo,index)=><li key={index} >{todo}</li>)}
				</ul>
			)
		}
	}
	List.prototypes={
		todos:PropTypes.array.isRequired
	}
	ReactDOM.render(
		<App />,
		document.getElementById('example')
	);
</script>

</body>
</html>